#!/bin/bash

if [[ ! -z "${LOG_LEVEL}" ]]; then
  set -ex
else
  set -CeE
fi
set -o pipefail
set +o noclobber

echo "============================================="
if [[ ! -z "${OUTPUT_DIR}" ]]; then
  OUTPUT_DIR_FINAL=${OUTPUT_DIR}
fi

source ".currContext"

if [[ ! -z "${OUTPUT_DIR_FINAL}" ]]; then
  OUTPUT_DIR=${OUTPUT_DIR_FINAL}
fi

cd ${OUTPUT_DIR}
echo "Cleanup and Detach VM ${1}"
if [[ ! -e "vm-${1}/.context" ]]; then
  fatal "file vm-${1}/.context does not exists in most recent used output directory set by create context.
  export OUTPUT_DIR to the directory you used to attach the VM ${1} then re-run cleanup_vm"
fi
source "vm-${1}/.context"

echo -e "\e[1m[NOTICE]\e[0m user should manually delete namespace: "${VM_NAMESPACE}" and service-account: "${SERVICE_ACCOUNT}" if no other resource is sharing it."

echo "[Step 1] Delete VM Registration in Bare Metal Cluster ${CLUSTER}"
kubectl delete workloadentry "${VM_APP}-${VM_IP}-${VM_NETWORK}" -n ${VM_NAMESPACE} --ignore-not-found
kubectl delete workloadgroup ${VM_APP} -n ${VM_NAMESPACE} --ignore-not-found
kubectl delete service ${VM_APP} -n ${VM_NAMESPACE} --ignore-not-found

echo "[Step 2] Stop Istio on VM and Wipe out Mounted Artifacts"
cd ${WORK_DIR}
if [[ ! -e "vsphere/stopagent.sh" ]]; then
  fatal "file vsphere/stopagent.sh does not exists in working dir ${WORK_DIR}"
fi

scp -i "${KEY_FILE}" -o StrictHostKeyChecking=no vsphere/stopagent.sh root@${VM_IP}:"${VM_DIR}"
stopagentcmd="chmod +x ${VM_DIR}/stopagent.sh; ${VM_DIR}/stopagent.sh ${VM_DIR} >/dev/null"
until ssh -i "${KEY_FILE}" -o StrictHostKeyChecking=no root@${VM_IP} ${stopagentcmd}; do
  sleep 1
done

echo "[Step 3] Remove folder ${OUTPUT_DIR}/vm-${VM_APP}"
rm -rf ${OUTPUT_DIR}/vm-${VM_APP}

echo -e "\xE2\x9C\x94 Successfully Cleanup vm:${VM_APP} addr:${VM_IP}"
